package edu.whu.notepal.controller;


import cn.hutool.core.util.StrUtil;
import edu.whu.notepal.dto.Result;
import edu.whu.notepal.dto.UserDTO;
import edu.whu.notepal.pojo.User;
import edu.whu.notepal.service.UserService;
import edu.whu.notepal.utils.PasswordEncoder;
import edu.whu.notepal.utils.RedisClient;
import edu.whu.notepal.utils.RedisConstants;
import edu.whu.notepal.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @description 用户控制器方法
 * @author 陈磊
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    UserService userService;

    @Resource
    RedisClient redisClient;

    /**
     * 获取验证码的方法
     * @param email 邮箱号
     * @return 提示信息
     */
    @GetMapping("/code")
    public Result<String> getCode(@RequestParam("email")String email){
        userService.getCode(email);
        return Result.success("验证码发送成功！");
    }

    /**
     * 登录的方法 可以选择验证码或者密码登录
     * @param userDTO
     * @return
     */
    @PostMapping("/login")
    public Result<String> login(@RequestBody UserDTO userDTO){
        String token = userService.login(userDTO);
        return Result.success(token);
    }

    @PostMapping("/me")
    public Result<User> me(){
        return Result.success(UserHolder.getUser());
    }

    @PostMapping("/register")
    public Result<String> register(@RequestBody UserDTO userDTO){
        userService.register(userDTO);
        return Result.success("保存成功！");
    }

    /**
     * redis缓存中数据也要更新
     * @param user
     * @return
     */
    @PutMapping
    public Result<String> update(HttpServletRequest request,@RequestBody User user){
        user.setId(UserHolder.getUser().getId());
        if(StrUtil.isEmpty(user.getIcon())){
            user.setIcon(null);
        }
        redisClient.deleteKey(RedisConstants.USER_INFO_KEY,user.getId());
        if(StrUtil.isNotEmpty(user.getPassword())){
            user.setPassword(PasswordEncoder.encode(user.getPassword()));
        }
        userService.updateById(user);
        String token = request.getHeader("authorization");
        userService.addUser2Redis(token,user);
        return Result.success("修改成功！");
    }

    @GetMapping("/{id}")
    public Result<User> getById(@PathVariable("id")Long id){
        User user = redisClient.queryWithPassThrough(RedisConstants.USER_INFO_KEY,
                id, User.class, userService::getById, RedisConstants.USER_INFO_TTL, TimeUnit.DAYS);
        user.setPassword(null);
        return Result.success(user);
    }

}